<script setup>
name: 'roles'
import { ref, onMounted, reactive } from 'vue'
import { getRolesListAPI, getRightsListAPI, delRolesAuthorityAPI, addRolesAPI, editRolesAPI, delRolesAPI, grantRolesAPI } from '@/api/authorityAPI'
import { ElMessage, ElMessageBox } from 'element-plus';

// 获取角色列表数据
const rolesList = ref([])
const getRolesList = async () => {
    const { data: res } = await getRolesListAPI()
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    rolesList.value = res.data
}
// 获取权限列表
const rightsList = ref([])
const getRightsList = async (type) => {
    const { data: res } = await getRightsListAPI(type)
    console.log(res);
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    rightsList.value = res.data
}

// 删除角色权限
const delRolesAuthority = async (row, rightId) => {
    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).catch(err => err)
    if (confirmResult === 'confirm') {
        const { data: res } = await delRolesAuthorityAPI(row.id, rightId)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        console.log(row.children);
        row.children = res.data
    } else {
        ElMessage.info('用户取消操作')
    }
}

// 添加角色
const rules = reactive({
    roleName: [
        { required: true, message: '请输入角色名', trigger: 'blur' },
    ]
})
const roleRef = ref(null)
const roleDialogVisible = ref(false)
const roleForm = ref({
    roleName: '',
    roleDesc: ''
})
const roleDialogClose = () => {
    roleRef.value.resetFields()
}
const addRole = () => {
    roleRef.value.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await addRolesAPI(roleForm.value)
        if (res.meta.status !== 201) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        roleDialogVisible.value = false
        getRolesList()
    })

}

// 修改角色
const editDialogVisible = ref(false)
const editFrom = ref({
    id: '',
    roleName: '',
    roleDesc: ''
})
const editRef = ref(null)

const editDialog = (role) => {
    const { id, roleName, roleDesc } = role
    editFrom.value = { id, roleName, roleDesc }
    editDialogVisible.value = true
}

const editDialogClose = () => {
    editRef.value.resetFields()
}
const editRole = () => {
    editRef.value.validate(async (valid) => {
        if (valid) {
            const { data: res } = await editRolesAPI(editFrom.value)
            if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
            ElMessage.success(res.meta.msg)
            editDialogVisible.value = false
            editFrom.value = {
                id: '',
                roleName: '',
                roleDesc: ''
            }
            getRolesList()
        }
    })
}

// 删除角色
const delRoles = async (id) => {
    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).catch(err => err)
    if (confirmResult === 'confirm') {
        const { data: res } = await delRolesAPI(id)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        getRolesList()
    } else {
        ElMessage.info('已取消删除')
    }
}

// 分配权限
const grantDialogVisible = ref(false)
const defKeys = ref([])
const roleId = ref('')
const grantDialog = (row) => {
    getRightsList('tree')
    roleId.value = row.id
    grantDialogVisible.value = true
    getLeafKeys(row, defKeys.value)
}
const getLeafKeys = (node, arr) => {
    if (!node.children) {
        return arr.push(node.id)
    }
    node.children.forEach(item => getLeafKeys(item, arr))
}
const grantDialogClose = () => {
    defKeys.value = []
    roleId.value = ''
}
const treeRef = ref(null)
const grantRole = async () => {
    // console.log(treeRef.value.getCheckedKeys());
    // console.log(treeRef.value.getHalfCheckedKeys());
    defKeys.value = [...treeRef.value.getCheckedKeys(),...treeRef.value.getHalfCheckedKeys()]
    const rids = defKeys.value.join(',')
    const {data:res} = await grantRolesAPI(roleId.value,rids)
    if(res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    ElMessage.success(res.meta.msg)
    grantDialogVisible.value = false
    getRolesList()

 }

const treeProps = {
    children: 'children',
    label: 'authName',
}

onMounted(() => {
    getRolesList()
})

</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-button type="primary" @click="roleDialogVisible = true">添加角色</el-button>
        <el-table :data="rolesList" style="width: 100%" row-key="id" stripe border lazy>
            <el-table-column type="expand">
                <template #default="props">
                    <el-row v-for=" (I1, index) in props.row.children" :key="I1.id" class="bottomLine line"
                        :class="{ topLine: index === 0 }">
                        <el-col :span="5">
                            <el-tag closable @close="delRolesAuthority(props.row, I1.id)" disable-transitions>{{ I1.authName
                            }}</el-tag>
                            <el-icon>
                                <CaretRight />
                            </el-icon>
                        </el-col>
                        <el-col :span="19">
                            <el-row v-for="I2 in I1.children" :key="I2.id">
                                <el-col :span="6" class="line">
                                    <el-tag type="success" closable @close="delRolesAuthority(props.row, I2.id)"
                                        disable-transitions>{{
                                            I2.authName }}</el-tag>
                                    <el-icon>
                                        <CaretRight />
                                    </el-icon>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag type="warning" v-for="I3 in I2.children" :key="I3.id" closable
                                        @close="delRolesAuthority(props.row, I3.id)" disable-transitions>{{ I3.authName
                                        }}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleDesc" label="角色描述" />
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type="primary" icon="Edit" size="small" @click="editDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="Delete" size="small" @click="delRoles(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="Tools" size="small" @click="grantDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog v-model="roleDialogVisible" title="添加角色" width="50%" @close="roleDialogClose">
        <el-form :model="roleForm" label-width="120px" :rules="rules" ref="roleRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="详细">
                <el-input v-model="roleForm.roleDesc" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addRole">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户" width="50%" @close="editDialogClose">
        <el-form :model="editFrom" label-width="120px" :rules="rules" ref="editRef">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editFrom.roleName" />
            </el-form-item>
            <el-form-item label="详细">
                <el-input v-model="editFrom.roleDesc" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="editRole">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog v-model="grantDialogVisible" title="分配权限" width="50%" @close="grantDialogClose">
        <el-tree :data="rightsList" node-key="id" :props="treeProps" default-expand-all show-checkbox
            :default-checked-keys="defKeys" ref="treeRef" />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="grantDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="grantRole">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-tag {
    margin: 7px;
}

.line {
    display: flex;
    align-items: center;
}

.bottomLine {
    border-bottom: 1px solid #eee;
}

.topLine {
    border: 1px solid #eee;
}
</style>